package com.dayouzi.esaydata.service.impl;

import com.dayouzi.esaydata.base.exception.Assert;
import com.dayouzi.esaydata.base.result.ResponseEnum;
import com.dayouzi.esaydata.mapper.UserAdminMapper;
import com.dayouzi.esaydata.pojo.entity.UserAdmin;
import com.dayouzi.esaydata.pojo.vo.LoginDTO;
import com.dayouzi.esaydata.pojo.vo.LoginVO;
import com.dayouzi.esaydata.service.LoginService;
import com.dayouzi.esaydata.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author DaYouZi
 * @since 2023-03-06
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserAdminMapper userAdminMapper;

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        String userName = loginDTO.getUsername();
        String password = loginDTO.getPassword();

        //从数据库获取用户信息
        UserAdmin userAdmin = userAdminMapper.getInfoByUserName(userName);

        //判断用户是否存在
        Assert.notNull(userAdmin, ResponseEnum.LOGIN_MOBILE_ERROR);

        //判断密码是否正确
        Assert.equals(password, userAdmin.getPassword(), ResponseEnum.LOGIN_PASSWORD_ERROR);

        //记录用户登录日志
        //TODO

        //生成token
        String token = JwtUtils.createToken(Long.valueOf(userAdmin.getId()), userAdmin.getUserName());
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        return loginVO;
    }

    @Override
    public String[] getRole(String userName) {
        //从数据库获取用户信息
        UserAdmin userAdmin = userAdminMapper.getInfoByUserName(userName);
        String roleName = "";
        Integer roleCode = userAdmin.getRole();
        switch (roleCode) {
            case 0:
                roleName = "admin";
                break;
            case 1:
                roleName = "user";
                break;
            default:
                break;
        }
        return new String[]{roleName};
    }
}
